package com.sqly.doc.ble.xty;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sqly.doc.R;
import com.sqly.doc.base.BaseHolder;
import com.sqly.doc.base.BaseRecyclerViewAdapter;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.pojo.BleEntity;
import com.sqly.doc.util.MyApplication;
import com.sqly.doc.util.ToastUtil;
import com.vivachek.nova.bleproxy.BleProxy;
import com.vivachek.nova.bleproxy.BluetoothBroadcastReceiver;
import com.vivachek.nova.bleproxy.annotation.BleConnectState;
import com.vivachek.nova.bleproxy.entity.BaseBluetooth;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class BleFindActivity_bak extends MyBaseActivity {
	private static final String TAG = "WdBleFindActivity";

	public static final int PERMISSION = 1;

	private RecyclerView mRv;
	private TextView mTvResearch, title;
	private BaseRecyclerViewAdapter<BleEntity> mAdapter;
	private List<String> mScanMac = new ArrayList<>();
	LinearLayout back;

	@Override
	protected void initUI() {
		setContentView(R.layout.activity_wdblefind);
		title = (TextView) findViewById(R.id.title);
		back = (LinearLayout) findViewById(R.id.back);
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		title.setText("血糖仪设备");
		mTvResearch = findViewById(R.id.uname);
		mRv = findViewById(R.id.rv);
		mTvResearch.setText("正在搜索");

		mAdapter = new BaseRecyclerViewAdapter<BleEntity>(R.layout.item_search_ble) {

			@Override
			protected void convert(BaseHolder holder, BleEntity bleEntity) {
				holder.setIsRecyclable(false);
				holder.setText(R.id.tvDeviceName,
						String.format(getString(R.string.device_name),
								bleEntity.getBluetooth().getDevice().getName()));
				holder.setText(R.id.tvDeviceMac, String.format(getString(R.string.device_mac),
						bleEntity.getBluetooth().getDevice().getAddress()));
				holder.setText(R.id.tvDeviceSn, String.format(getString(R.string.device_sn),
						bleEntity.getBluetooth().getSn()));
				if (bleEntity.getState() == BleConnectState.DISCONNECTED) {
					holder.setVisible(R.id.pb, View.GONE);
				} else if (bleEntity.getState() == BleConnectState.CONNECTING) {
					holder.setVisible(R.id.pb, View.VISIBLE);
					ProgressBar pb = holder.getViewById(R.id.pb);
					pb.setIndeterminateDrawable(ActivityCompat.getDrawable(MyApplication.getApp(), R.drawable.anim_connecting));
					pb.setProgressDrawable(ActivityCompat.getDrawable(MyApplication.getApp(),
							R.drawable.anim_connecting));
				} else if (bleEntity.getState() == BleConnectState.CONNECT_SUCCESS) {
					holder.setVisible(R.id.pb, View.VISIBLE);
					ProgressBar pb = holder.getViewById(R.id.pb);
					pb.setIndeterminateDrawable(ActivityCompat.getDrawable(MyApplication.getApp(),
							R.drawable.connect_success));
					pb.setProgressDrawable(ActivityCompat.getDrawable(MyApplication.getApp(),
							R.drawable.connect_success));
				}
			}
		};
		mRv.setAdapter(mAdapter);
		mRv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
		mAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener<BleEntity>() {
			@Override
			public void onItemClick(BaseHolder holder, BleEntity bleEntity, int position) {
				for (BleEntity entity : mAdapter.getData()) {
					entity.setState(BleConnectState.DISCONNECTED);
				}
				bleEntity.setState(BleConnectState.CONNECTING);
				mAdapter.notifyDataSetChanged();
				BleProxy.getInstance().connect(bleEntity.getBluetooth().getDevice().getAddress());
			}
		});
		mTvResearch.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				scanBluetooth();
			}
		});
	}

	@Override
	protected void initData() {

	}

	@Override
	protected void initListener() {

	}

	private BluetoothBroadcastReceiver mReceiver = new BluetoothBroadcastReceiver() {
		@Override
		protected void bluetoothDeviceDisconnected() {

		}

		@Override
		protected void bluetoothIsClose() {

		}

		@Override
		protected void bluetoothIsOpen() {
			BleProxy.getInstance().scan();
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		IntentFilter filter = new IntentFilter();
//		监视蓝牙关闭和打开的状态
		filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
//		监视蓝牙设备与APP连接的状态
		filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
		filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
		registerReceiver(mReceiver,filter);


		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			int bluetooth = ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH);
			int bluetoothAdmin = ActivityCompat.checkSelfPermission(this,
					Manifest.permission.BLUETOOTH_ADMIN);
			int location = ActivityCompat.checkSelfPermission(this,
					Manifest.permission.ACCESS_COARSE_LOCATION);
			if (bluetooth == PackageManager.PERMISSION_GRANTED && bluetoothAdmin == PackageManager.PERMISSION_GRANTED && location == PackageManager.PERMISSION_GRANTED) {
				scanBluetooth();
			} else {
				requestPermissions(new String[]{Manifest.permission.BLUETOOTH,
						Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION);
			}

		}else {
			scanBluetooth();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);
	}

	private void scanBluetooth() {
		mScanMac.clear();
		mAdapter.clearData();
		mAdapter.notifyDataSetChanged();
		if (BleProxy.getInstance().isBleEnable()) {
			BleProxy.getInstance().scan();
		}else {
			BleProxy.getInstance().enableBle();
		}
	}

	@Override
	public void onScanStart() {
		super.onScanStart();
		mTvResearch.setText(getString(R.string.searching));
		mTvResearch.setClickable(false);
	}

	@Override
	public void onScanFinish(List<BaseBluetooth> scanResultList) {
		super.onScanFinish(scanResultList);
		mTvResearch.setText(getString(R.string.research));
		mTvResearch.setClickable(true);
	}

	@Override
	public void onScanning(BaseBluetooth bleDevice) {
		Log.i("onScanning","================2");
		super.onScanning(bleDevice);
		if (bleDevice == null) {
			return;
		}
		String mac = bleDevice.getDevice().getAddress();
		String name = bleDevice.getDevice().getName();
		if (TextUtils.isEmpty(mac) || TextUtils.isEmpty(name)) {
			return;
		}
		BleEntity bleEntity = new BleEntity(bleDevice, BleConnectState.DISCONNECTED);
		boolean isNotify = false;
		if (mScanMac.contains(mac)) {
			for (BleEntity entity : mAdapter.getData()) {
				if (entity.getBluetooth().getDevice().getAddress().equals(mac)) {
					String sn = entity.getBluetooth().getSn();
					if (TextUtils.isEmpty(sn)) {
						entity.getBluetooth().setSn(bleDevice.getSn());
						isNotify = true;
						break;
					}
				}
			}
			if (isNotify) {
				mAdapter.notifyDataSetChanged();
			}
		} else {
			mScanMac.add(mac);
			mAdapter.addData(bleEntity);
			mAdapter.notifyDataSetChanged();
		}
//		此处可以自动连接蓝牙设备
//		for (BleEntity entity : mAdapter.getData()) {
//			entity.setState(BleConnectState.DISCONNECTED);
//			if("69:9B:F2:61:08:D9".equals(entity.getBluetooth().getDevice().getAddress())){
//				bleEntity.setState(BleConnectState.CONNECTING);
//				BleProxy.getInstance().connect(bleEntity.getBluetooth().getDevice().getAddress());
//			}
//		}
	}

	@Override
	public void onConnectSuccess(BaseBluetooth bleDevice) {
		Log.i("onConnectSuccess","================1");
		super.onConnectSuccess(bleDevice);
		for (BleEntity entity : mAdapter.getData()) {
			if (entity.getBluetooth().getDevice().getAddress().equals(bleDevice.getDevice().getAddress())) {
				entity.setState(BleConnectState.CONNECT_SUCCESS);
			} else {
				entity.setState(BleConnectState.DISCONNECTED);
			}
		}
		mAdapter.notifyDataSetChanged();
		BleProxy.getInstance().notify(bleDevice);

	}

	@Override
	public void openNotifySuccess(BaseBluetooth bleDevice) {
		Log.i("openNotifySuccess","================3");
		super.openNotifySuccess(bleDevice);
		Intent intent = new Intent(this, ControlActivity.class);
		intent.putExtra(ControlActivity.DEVICE, (Serializable) bleDevice);
		startActivity(intent);
//		finish();
	}

	@Override
	public void openNotifyFail() {
		super.openNotifyFail();
		for (BleEntity entity : mAdapter.getData()) {
			entity.setState(BleConnectState.DISCONNECTED);
		}
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void onConnectFail(String mac) {
		super.onConnectFail(mac);
		for (BleEntity entity : mAdapter.getData()) {
			entity.setState(BleConnectState.DISCONNECTED);
		}
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if (requestCode == PERMISSION) {
			for (int i = 0; i < permissions.length; i++) {
				if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
					ToastUtil.showShortToast(MyApplication.getApp(), getString(R.string.permission_denied));
					return;
				}
			}
			scanBluetooth();
		} else {
			ToastUtil.showShortToast(MyApplication.getApp(), getString(R.string.permission_denied));
		}
	}

	@Override
	public void onPointerCaptureChanged(boolean hasCapture) {

	}
}
